const express = require("express");
//创建路由
let lifemoment = express.Router();
//路径包
const path = require("path");
//获取启动项目录
const rootDir = process.cwd();
//用于临时令牌
const crypto = require('crypto');
const jwt = require('jsonwebtoken');

//引入方法
//引入授权中间件
const authenticateToken = require(path.join(rootDir, "/middlewares/authMiddleware"));
//引入上传图片中间件
const uploadfile = require(path.join(rootDir, "/middlewares/uploadMiddleware"));
//引入移动检测中间件
const mobiledetect = require(path.join(rootDir, './middlewares/mobiledetect'));

//引入数据表
let lifeloki = require(path.join(rootDir, "lokisheets/lifeDB"));

//定义文件保存路径
//生活瞬间封面
let lifeCoverUrl = { "image": path.join("lifeMoment", "lifeCover") }

//创建中间件
//旅行记录封面图片限制中间件
const lifecoverUpload = uploadfile.createUploader(lifeCoverUrl, {
    //限制文件类型
    allowedMimeTypes: ['image/jpeg', 'image/png', 'image/webp'],
    //限制文件大小
    limits: { fileSize: 40 * 1024 * 1024 }
});

// 旅行记录封面和验证中间件
let lifemiddlewares = [
    authenticateToken.authenticateToken,
    lifecoverUpload.single('image')
];

// 生成一次性临时认证码
const tempTokens = new Map();


//区分手机电脑页面中间件
lifemoment.use(mobiledetect);

//生活瞬间根路由
lifemoment.get("/", (req, res) => {
    //process.cwd()是启动文件的绝对路径
    if (req.isMobile) {
        //这是手机端页面
        res.sendFile(process.cwd() + "/static/html/mobile/lifemoment/lifemomentindex.html");
    } else {
        //这是电脑端页面
        res.sendFile(process.cwd() + "/static/html/computer/lifemoment/lifemomentindex.html");
    }
});

//创建生活瞬间展示路由
lifemoment.use("/createshow", (req, res) => {
    if (req.isMobile) {
        //这是手机端页面
        res.sendFile(process.cwd() + "/static/html/mobile/lifemoment/lifemomentcreate.html");
    } else {
        //这是电脑端页面
        res.sendFile(process.cwd() + "/static/html/computer/lifemoment/lifemomentcreate.html");
    }
});

//创建生活瞬间路由
lifemoment.use("/createlife", lifemiddlewares, async (req, res) => {
    try {
        //修改这里的保存信息
        let webData = { ...req.body, ...req.query };
        //验证上传过来的数据

        //保存数据
        let saveData = {
            User_id: req.user.userid, // 从请求对象中获取用户ID
            // 表数据
            Lifename: webData.Lifename, //生活瞬间标题
            Lifemessage: webData.Lifemessage, //生活瞬间寄语
        }

        if (req.file)
            saveData.Lifecovername = req.file.originalname; //上传图片名称
        if (req.file)
            saveData.Lifecoverurl = req.file.path; //上传图片路径

        let result = await lifeloki.create(saveData);
        if (result.success) {
            res.json({ message: { success: true, data: result } });
        } else {
            res.json({ message: { success: false, data: "创建失败" } });
        }
    } catch (error) {
        res.json({ message: { success: false, data: "程序错误", error: error.message } });
    }

});

//查找生活瞬间路由
lifemoment.use("/findlife", authenticateToken.authenticateToken, async (req, res) => {
    try {
        let webData = { ...req.body, ...req.query };

        const User_id = req.user.userid;
        let findData = {
            condition: {
                $and: [
                    { User_id },
                    webData.condition
                ]
            },
            limit: webData.limit
        }

        let result = await lifeloki.find(findData.condition);
        if (result.success) {
            res.json({ message: { success: true, data: result.data } });
        } else {
            res.json({ message: { success: false, data: "查询不到数据" } });
        }
    } catch (error) {
        res.json({ message: { success: false, data: "错误处理", err: error } });
    }
});

//更新生活瞬间路由
lifemoment.use("/updatalife", lifemiddlewares, async (req, res) => {
    //修改这里的保存信息
    let webData = { ...req.body, ...req.query };

    //保存数据
    let saveData = {
        //查找条件
        User_id: req.user.userid,
        Life_id: webData.Life_id,
        // 更新数据
        Lifename: webData.Lifename, //生活瞬间标题
        Lifemessage: webData.Lifemessage, //生活瞬间寄语
    }

    if (req.file)
        saveData.Lifecovername = req.file.originalname; //上传图片名称
    if (req.file)
        saveData.Lifecoverurl = req.file.path; //上传图片路径


    let result = await lifeloki.update(saveData);
    if (result.success) {
        res.json({ message: { success: true, data: result } });
    } else {
        res.json({ message: { success: false, data: "更新失败" } });
    }
});

//删除生活瞬间路由
lifemoment.use("/deletelife", authenticateToken.authenticateToken, async (req, res) => {
    let webData = { ...req.body, ...req.query };

    let findData = {
        User_id: req.user.userid,
        Life_id: webData.Life_id
    }

    let result = await lifeloki.delete(findData);
    if (result.success) {
        res.json({ message: { success: true, data: result } });
    } else {
        res.json({ message: { success: false, data: "删除失败" } });
    }
});

//返回一次性临时认证码
lifemoment.use('/gettempcode', (req, res) => {
    try {
        const authHeader = req.headers.authorization;
        if (!authHeader) return res.status(401).send('未授权');

        // 解码原始令牌获取用户信息
        const originalToken = authHeader.split(' ')[1];

        const decoded = jwt.verify(originalToken, process.env.JWT_SECRET);
        let userid = decoded.userid;

        // 创建临时令牌并存储完整用户信息
        const tempToken = crypto.randomBytes(32).toString('hex');

        tempTokens.set(tempToken, {
            userid,
            originalToken,
            expiresAt: Date.now() + 60 * 60 * 1000 // 60分钟后过期
        });

        res.json({ tempToken });
    } catch (err) {
        console.error("Token 验证失败:", err);
        res.status(401).json({ error: "无效的 Token" });
    }
});

//编辑生活瞬间路由
lifemoment.use("/edit:name", async (req, res) => {
    const tempToken = req.query.tempToken;

    // 1. 检查临时令牌是否存在
    if (!tempTokens.has(tempToken)) {
        return res.status(401).json({ error: "无效的临时令牌" });
    }

    const tokenData = tempTokens.get(tempToken);

    if (!tokenData || tokenData.expiresAt < Date.now()) {
        tempTokens.delete(tempToken);
        return res.status(401).send('无效或过期的临时令牌');
    }
    let life_id = req.params.name;
    // // 直接使用存储的用户ID
    const userId = tokenData.userid;
    //查找数据
    let findData = {
        User_id: userId,
        Life_id: life_id
    }
    let result = await lifeloki.find(findData);

    if (!result.data[0]) {
        res.send("不存在数据");
    }
    else {
        if (req.isMobile) {
            //这是手机端页面
            res.render("mobile/lifemomentejs/lifemomentedit", { json: result.data[0] });
        } else {
            //这是电脑端页面
            res.render("computer/lifemomentejs/lifemomentedit", { json: result.data[0] });
        }
    }
});

module.exports = lifemoment;